<?php
class TbfRand {
    //安全级随机字母
    static function SecurityLetter($len){
        $list = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T',
            'U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n',
        'o','p','q','r','s','t','u','v','w','x','y','z',);
        return self::SecurityFromList($list,$len);
    }
    static function SecurityFromList(array $list,$len)
    {
        $listLen = count($list);
        $listMax = $listLen-1;
        $data = '';
        for ($i=0;$i<$len;$i++) {
            $data .= $list[self::SecurityInt() % $listMax];
        }
        return $data;
    }
    static function SecurityInt(){
        $data = self::SecurityBinary(4);
        $unpacked = unpack('N',$data);
        return $unpacked[1];
    }
    //密码级随机
    static function SecurityBinary($len){
        if (function_exists('openssl_random_pseudo_bytes')) {
            //先找openssl
            $r = openssl_random_pseudo_bytes($len,$tmp);
            if ($r!==FALSE) {
                return $r;
            }
        }
        if (file_exists('/dev/urandom')) {
            //再去找系统
            $r =  fread(fopen('/dev/urandom', 'r'),$len);
            if (!empty($r)) {
                return $r;
            }
        }
        throw new Exception('not crypto function');
    }
}
